import axios from 'axios'
import cookies from 'libs/cookies';

import { ElMessage,ElLoading} from 'element-plus'

import type { AxiosInstance,AxiosRequestConfig,AxiosRequestHeaders,AxiosResponse ,AxiosError } from 'axios'
axios.defaults.withCredentials = true;

let cancelToken = axios.CancelToken
let pending = { key: '', date: 0 };// 网络请求记录map结构

class NetWork {
    instance: AxiosInstance
    baseUrl:string
    loadingInstance:any
    constructor() {
        this.baseUrl = import.meta.env.GZG_BASE_URL
        this.instance = axios.create()

        this.instance.interceptors.request.use(
            (config) => {
                config.withCredentials = true
                const timestamp = (new Date().getTime()) / 1000;

                let key = '';
                
                if (config.method == 'post') {
                    key =  `${config.url}&${config.method}&${JSON.stringify({...config.data, timestamp: '' })}`

                } else {
                    key =  `${config.url}&${config.method}&${JSON.stringify({...config.params, timestamp: '' })}`

                }
                // config.cancelToken = new cancelToken(c => {
                //     if (pending.key == key) {
                //         if (Date.now() - pending.date < 1000) c("");
                //     }
                //     pending = { key: key, date: Date.now() }
                // })

                const token = cookies.get('token')
                config.url = `${this.baseUrl + config.url}`
                if (token) {
                    config.headers["x-token"] = token

                }
                if (config.method === 'get') {
                    let params = config.params || {}
                    if (token) {
                        params.token = token
                    }
                    params.timestamp = timestamp
                    config.params = params
                } else {
                    let data = config.data || {}
                    data.token = token
                    data.timestamp = timestamp
                    config.data = JSON.parse(JSON.stringify(data))
                    if (token) {
                        config.url = config.url + '?token=' + token
                    }
                    this.loadingInstance = ElLoading.service({
                        fullscreen:true,
                        lock:true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.5)'
                    })
                }
                // if (token) {
                //   config.headers['x-token'] = token
                // }
                
                return config
            },
            (error:AxiosError) => {
                this.loadingInstance.close()
                Promise.reject(error)
            }
        )

        this.instance.interceptors.response.use((response:AxiosResponse) =>  {
            this.loadingInstance?.close()
            const dataAxios = response.data
            const {code}  = dataAxios
            switch (code) {
                case 0:
                    return dataAxios.data;
                case 401:
                    ElMessage.error(`${dataAxios.msg || '系统错误'}`)

                    window.location.href = '/login'
                    return
                default:
                    ElMessage.error(`${dataAxios.msg || '系统错误'}`)
                    return Promise.reject(dataAxios.msg)
            }
        }, (error:AxiosError) => {
            this.loadingInstance.close()
            
            ElMessage.error(`${error.message || '系统错误'}`)

            return Promise.reject(error)

        })
    }
}

export default new NetWork().instance